let logger = require("pomelo-logger").getLogger(__filename);
let gameCreator = require("../entities/game").create;
let Random = require("../../utils/random");

let CODES = [];
for (let i = 100000; i <= 999999; i++) {
    CODES.push('' + i);
}

let GameService = function (app) {
    this.games = {};
    this.codeToGid = {};
};

GameService.prototype.initialize = function (cfg) {
    for (let index in cfg) {
        let gameCfg = cfg[index];
        let game = gameCreator(gameCfg);
        this.games[game.getGid()] = game;
    }
};

GameService.prototype.getGameById = function (gid) {
    if (this.games.hasOwnProperty(gid)) {
        return this.games[gid];
    }
    return null;
};

GameService.prototype.toJSON = function () {
    var data = [];
    for (var gid in this.games) {
        data.push(this.games[gid]);
    }
    return data;
};

GameService.prototype.genCode = function (game) {
    let code = this.doGenCode();
    if (code.length > 0) {
        this.codeToGid[code] = game.getGid();
    }
    return code;
};

GameService.prototype.clearCode = function (codes) {
    for (let code of codes) {
        delete this.codeToGid[code];
    }
};

GameService.prototype.getGidByCode = function (code) {
    if (this.codeToGid.hasOwnProperty(code)) {
        return this.codeToGid[code];
    } else {
        return 0;
    }
};

GameService.prototype.doGenCode = function () {
    let iterTimes = 0;
    do {
        let code = Random.choice(CODES);
        if (!this.codeToGid.hasOwnProperty(code)) {
            return code;
        }
        iterTimes = iterTimes + 1;
        if (iterTimes >= 10) {
            logger.error("generatorCode error");
            return "";
        }
    } while (true);
};

module.exports.create = function (app) {
    return new GameService(app);
};
